<template>
    <div style="height:100%;">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-child'>分类管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <div class='categoryClass'>
        <el-row>
          <el-button type="warning" style="float:right;margin-right:20px" @click="addVisable = true">添加</el-button>
        </el-row>
        <el-row style="margin-top:10px" >
          <el-table
            v-loading="loading"
            :element-loading-text="loadingText"
            element-loading-spinner="el-icon-loading"
            :data="filterFormFro.tableData" 
            :border="true"
            :row-class-name="tableRowClassName"
            :header-cell-class-name = "tableHeaderClassName"
            v-bind:style="{width: tableWidth + 'px'}">
              <el-table-column prop="index" label="序号" min-width=10%>
              </el-table-column>
              <el-table-column prop="name" label="分类名称" min-width=30%>
              </el-table-column>
              <el-table-column prop="number" label="排序编号" min-width=10%>
              </el-table-column>
              <el-table-column prop="num" label="数量" min-width=20%>
              </el-table-column>
              <el-table-column label="操作" min-width=40%>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
            <el-pagination
              @current-change="handleCurrentChange"
              background
              :current-page="filterFormTo.currentPage"
              :page-size="15"
              layout="total, prev, pager, next"
              :page-count="filterFormFro.totalPage"
              :background="true">
            </el-pagination>
        </div>
        </el-row>
      </div>
      <!-- 添加分类信息弹窗 -->
      <el-dialog title="增加分类:"   :visible.sync="addVisable"
        class="categoryManaDialog"
        :closeOnClickModal="false" 
        width="550px"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
        @close="resetForm('addForm')">
        <el-form :model='addForm' :rules="addRules" ref="addForm">
            <el-form-item label="分类名称：" :label-width="formLabelWidth" prop="name">
              <el-input style='width:240px' @keyup.native="addForm.name=addForm.name.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable v-model.trim="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="number">
              <el-input style='width:240px' auto-complete="off" v-model="addForm.number" type="number"  ></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
             <el-button type="primary" style="width:240px;margin-top:20px" @click="submitAdd">保 存</el-button>
            </el-form-item>
        </el-form>
        <!-- <div style="clear:both;text-align:center">
          <el-button type="primary" style="width:240px;margin-top:20px" @click="addCategoryListFro()">保 存</el-button>
        </div> -->
        <!-- <div slot="footer" class="dialog-footer">
          <el-button @click="addVisable = false">取 消</el-button>
          <el-button type="info" @click="addCategoryListFro()">保 存</el-button>
        </div> -->
      </el-dialog>
      <!-- 编辑分类信息弹窗 -->
      <el-dialog title="编辑分类信息:"   :visible.sync="editVisable"
        :closeOnClickModal="false" 
        width="550px"
        class="categoryManaDialog"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
        @close="resetForm('editForm')">
        <el-form :model='editForm' ref="editForm" :rules="editRules">
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="number">
              <el-input style='width:240px' auto-complete="off" v-model="editForm.number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="分类名称：" :label-width="formLabelWidth" prop="name">
              <el-input style='width:240px' @keyup.native="editForm.name=editForm.name.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable v-model.trim="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
             <el-button type="primary" style="width:240px;margin-top:20px" @click="submitEdit()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<style scoped>
  .categoryClass {
    text-align:center;clear:both;height:100%;margin-top:10px
  }
  .el-table__body, .el-table__footer, .el-table__header {
  table-layout: auto !important;
  }
  .el-table__body-wrapper, .el-table__footer-wrapper, .el-table__header-wrapper{
  width: 101%;
  }
</style>
<script>
import '../../../static/css/businessPlat/categoryMana.css'
import '../../../static/css/businessPlat/common.css'
import apiBus from '../../api/businessPlat/apiBus.js'
export default {
  created () {
  },
  mounted () {
    this.getCategoryListFro()
    this.tableWidth = document.body.scrollWidth - 259 - 20
  },
  data () {
    var checkNumber = (rule, value, callback) => { // 分类排序编号验证
      if (value > 99) {
        callback(new Error('分类排序编号最大为99'))
      } else {
        callback()
      }
    }
    var checkInetger = (rule, value, callback) => { // 整数验证
      if (value % 1 === 0 && value > 0) {
        callback()
      } else {
        callback(new Error('请输入正整数'))
      }
    }
    return {
      tableWidth: '', // 表格宽度
      testData: [],
      testData2: [],
      paginationVisible: true, // 分页是否显示
      pointVisible: false, // 后台请求数据提示是否显示
      Note: '', // 后台请求数据提示
      loading: false, // 表格数据加载框
      loadingText: '正在拼命加载中，请稍等......',
      noteVisible: false,
      formLabelWidth: '170px',
      addForm: {
        name: '',
        number: '',
        index: 0
      },
      addVisable: false,
      filterFormTo: {
        currentPage: 1 // 当前页数
      },
      filterFormFro: {
        tableData: [],
        totalPage: 30 // 总共页数
      },
      editVisable: false,
      editForm: {
        name: '',
        num: '',
        number: '',
        index: 0,
        classId: ''
      },
      deleteForm: {
        classId: '',
        name: '',
        num: '',
        number: '',
        index: 0
      },
      addRules: {
        name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' },
          { max: 8, message: '分类名称最多8个字', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      },
      editRules: {
        name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' },
          { max: 8, message: '分类名称最多8个字', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /** 提交后台相关函数 */
    // 查看分类列表
    getCategoryListFro () {
      this.loading = true
      this.paginationVisible = false
      this.filterFormFro.tableData = []
      console.log(typeof (sessionStorage.getItem('token')))
      let para = {
        header: JSON.stringify({
          'token': sessionStorage.getItem('token'),
          'beanId': 'businessManageService_v1'
        }),
        body: JSON.stringify({
          'pageNum': parseInt(this.filterFormTo.currentPage)
        })
      }
      apiBus.getCategoryList(para).then(res => {
        this.loading = false
        console.log('getCategoryList回参')
        console.log(res)
        if (res.data.body.result === 1000) {
          if (res.data.body.content.list.length > 0) {
            this.$message.success('成功提取分类信息！')
            let resData = res.data.body.content.list
            this.filterFormFro.tableData = resData
            this.filterFormFro.totalPage = res.data.body.content.allPages
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterFormTo.currentPage) - 1) * 15 + i + 1
              this.filterFormFro.tableData[i].name = resData[i].className
              this.filterFormFro.tableData[i].number = resData[i].sortNum
              this.filterFormFro.tableData[i].num = resData[i].sonNum
            }
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.$message.warning('没有相关分类信息')
            this.paginationVisible = false
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 增加分类
    addCategoryListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          className: this.addForm.name,
          sortNum: parseInt(this.addForm.number)
        })
      }
      apiBus.addCategoryList(para).then(res => {
        this.addVisable = false
        if (res.data.body.result === 1000) {
          this.$message.success('成功添加分类')
          this.resetForm('addForm')
          this.filterFormTo.currentPage = 1
          this.getCategoryListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 编辑分类
    editCategoryListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          className: this.editForm.name,
          sortNum: parseInt(this.editForm.number),
          classId: parseInt(this.editForm.classId)
        })
      }
      apiBus.editCategoryList(para).then(res => {
        this.editVisable = false
        if (res.data.body.result === 1000) {
          this.$message.success('编辑分类成功！')
          this.resetForm('editForm')
          this.filterFormTo.currentPage = 1
          this.getCategoryListFro()
          this.editVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 删除分类
    deleteCategoryListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          classId: parseInt(this.deleteForm.classId)
        })
      }
      apiBus.deleteCategoryList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterFormTo.currentPage = 1
          this.getCategoryListFro()
          this.$message.success('成功删除该分类！')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 增加分类，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addCategoryListFro()
        } else {
          return false
        }
      })
    },
    // 编辑分类，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editCategoryListFro()
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterFormTo.currentPage = val
      this.getCategoryListFro()
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 表格中点击编辑按钮
    handleEdit (index, row) {
      this.editVisable = true
      this.editForm.index = index
      this.editForm.num = row.num
      this.editForm.number = row.number
      this.editForm.name = row.name.trim()
      this.editForm.classId = this.filterFormFro.tableData[index].classId
      this.editForm.className = this.filterFormFro.tableData[index].className
    },
    handleDelete (index, row) {
      this.deleteForm.num = row.num
      this.deleteForm.number = row.number
      this.deleteForm.name = row.name
      this.deleteForm.classId = this.filterFormFro.tableData[index].classId
      this.$confirm('确认删除该分类么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteCategoryListFro()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    }
  }
}
</script>